package com.action;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.HibernateException;

import com.Interfacese.BuyProductInterface;
import com.Interfacese.SaveUserByUserInterface;
import com.Interfacese.SearchByUserName;
import com.biz.UserMessageHandle;
import entities.Product;
import entities.Users;
import com.exception.*;
import com.factory.ProduceObject;

import java.util.*;
public class checkOutTheProductsAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		List<Integer> errorBuyMessage =(List)request.getAttribute("errorBuyMessage");
		if(errorBuyMessage==null){
			errorBuyMessage=new ArrayList();
			request.setAttribute("errorBuyMessage",errorBuyMessage);
		}else if(errorBuyMessage.size()>0){
			errorBuyMessage=null;
		}
		
		ServletContext sc=this.servlet.getServletContext();
		List<Product> allProducts=(List) sc.getAttribute("allProducts");
		HttpSession hs=request.getSession();
		Map<Integer,Integer> cart=(Map)hs.getAttribute("cart");
		
		ProduceObject po= new ProduceObject();
		SearchByUserName sbua = po.produceUserMessageHandle();
		String userName=hs.getAttribute("userName").toString();
		Users u =sbua.searchByName(userName);
		
		Set set = cart.keySet();
		Iterator itr = set.iterator();
		BuyProductInterface bpi = po.produceProductMessageHandle();
		int leaveNum=-1;
		while(itr.hasNext()){
			int key=(Integer)itr.next();
			Product p = allProducts.get(key-1);
			try{
			leaveNum=bpi.buyProduct(u, p, cart.get(key));
			if(leaveNum==0){
				synchronized (sc){
					allProducts.remove(p);
				}
			}
			}catch(ProductDontEnough pde){
				pde.printStackTrace();
				errorBuyMessage.add(key);
				return mapping.findForward("ProductDontEnough");
			}catch(MoneyDontEnough mde){
				mde.printStackTrace();
				return mapping.findForward("moneyDontEnough");
				
			}catch(HibernateException he){
				he.printStackTrace();
				return mapping.findForward("systemError");
				
			}
		}
		SaveUserByUserInterface subui = po.produceUserMessageHandle();
		subui.saveUser(u);
		return mapping.findForward("success");
	}

}
